package org.example.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cgwb6
 * @description TODO
 * @date 2025/6/27 15:54
 */

@Slf4j
public class NCService {

    public static String buildXml(Map<String, String> paramMap, String pub) throws Exception {

        if (CollUtil.isEmpty(paramMap)) {
            throw new RuntimeException("参数不能为空");
        }

        // 创建SOAP工厂
        MessageFactory messageFactory = MessageFactory.newInstance();

        // 创建SOAP消息
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();

        // 添加命名空间声明
        envelope.addNamespaceDeclaration("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
        envelope.addNamespaceDeclaration("pub", "http://pub.itf.ws.nc/PubWs");
        // 创建SOAP主体
        SOAPBody body = envelope.getBody();

        // 创建SOAP主体元素
        QName bodyName = new QName("http://pub.itf.ws.nc/PubWs", pub, "pub");
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

        // 创建子元素
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            SOAPElement element = bodyElement.addChildElement(entry.getKey());
            element.addTextNode(entry.getValue());
        }

        // 如果需要将SOAP消息转换为字符串
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        soapMessage.writeTo(outputStream);
        return outputStream.toString();

    }

    // 解析nc返回的参数
    public static String analysisXml(String respXml, String pub) {
        // 使用org.json库将XML转换为JSON
        JSONObject jsonObject = XML.toJSONObject(respXml);
        // 从JSON中获取<return>元素的数据
        JSONObject queryResult = jsonObject.getJSONObject("soap:Envelope")
                .getJSONObject("soap:Body")
                .getJSONObject("ns1:" + pub)
                .getJSONObject("return");
        Boolean success = queryResult.getBool("success");
        if (!success) {
            String message = queryResult.getStr("msg");
            log.error("调用失败, 失败原因:{}", message);
        }
        JSONArray data = queryResult.getJSONArray("data");
        // 将JSONArray转换为List<?>
        return JSON.toJSONString(data);
    }

    public static void main(String[] args) throws Exception {
        String xmlStr = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Header><ns0:Urc xmlns:ns0=\"http://ws.uap.nc/lang\"><ns0:datasource>design</ns0:datasource><ns0:userCode>0001A110000001A49FMS</ns0:userCode><ns0:langCode>simpchn</ns0:langCode></ns0:Urc></soap:Header><soap:Body><ns1:disableMaterialResponse xmlns:ns1=\"http://pub.itf.ws.nc/NcForMaterialWs\"><return>{\"msg\":\"物料停用失败\",\"success\":false}</return></ns1:disableMaterialResponse></soap:Body></soap:Envelope>";
        String s = analysisXml(xmlStr, "disableMaterialResponse");
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("userCode", "123");
        hashMap.put("workNo", "332514");
        String s1 = buildXml(hashMap, "uploadFiles");
        String post = HttpUtil.post("444444", s1);
        System.out.println(post);

        HttpRequest.post("aaaa")
                .setReadTimeout(1111)
                .setConnectionTimeout(22222)
                .body(s1).execute().body();
    }
}
